
//
//  WQPhotosViewCell.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/19.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

let WQPhotosViewCellID = "WQPhotosViewCell"

protocol WQPhotosViewCellDelegate: NSObjectProtocol {
    func photosViewDidTapImage()
}

class WQPhotosViewCell: UICollectionViewCell {
    
    weak var photoViewDelegate: WQPhotosViewCellDelegate?
    var photoURL: NSURL? {
        didSet {
            
            // 重置scrollView的content内容位置属性
            self.restScrollView()
            // 转换url
            guard let url = photoURL else {
                return
            }
//            print(url)
            guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString) else {
                print("图片缓存失败")
                return
            }
            //设置站位图片
            
            self.setPlaceHolderImageView(image)
            
            // 1. 异步加载大图 - sd_webImage 有一个功能，一但设置了 url，准备异步加载
            // 清除之前的图片/如果之前的图片也是异步下载，但是没有完成，取消之前的异步操作！
            // 如果 url 对应的图像已经被缓存，直接从磁盘读取，不会再走网络加载
            // 几乎所有的第三方框架，进度回调都是异步的！
            // 原因：
            // 1>. 不是所有的程序都需要进度回调
            // 2>. 进度回调的频率非常高，如果在主线程，会造成主线程的卡顿
            // 3>. 使用进度回调，要求界面上跟进进度变化的 UI 不多，而且不会频繁更新！

            photoView.sd_setImageWithURL(thumbnailChange2middleURL(url), placeholderImage: nil, options: [], progress: { (currentProgress, total) -> Void in
//                print("设置进度")
                
                dispatch_async(dispatch_get_main_queue()) {
                    
                self.placeHolderView.progress =  CGFloat(currentProgress) / CGFloat(total)
                }
                
                }) { (image, _, _, _) -> Void in
                    //判断图片是否下载成功
                    if image == nil {
                        SVProgressHUD.showInfoWithStatus("网络繁忙...")
                        return
                    }
                    //站位图片隐藏
                    self.placeHolderView.hidden = true
                    //设置中等图片的位置
                    self.setPhotoViewPositon(image)
                    
                
            }
            
        }
    }
    /// 创建站位图片，设置图片在中间
    private func setPlaceHolderImageView(image: UIImage) {
        placeHolderView.hidden = false
        placeHolderView.image = image
        placeHolderView.sizeToFit()
        placeHolderView.center = photosViewCellScrollView.center
//        print(placeHolderView.frame)
    }

    
    //设置图片显示的位置
    private func setPhotoViewPositon(image: UIImage) {
        let size = displaySize(image)

        

        if size.height < photosViewCellScrollView.bounds.height {//高度没有超过屏幕高度，中心显示
            //计算scrollView的偏移量
            let y = (photosViewCellScrollView.bounds.size.height - size.height) * 0.5
            photoView.frame = CGRectMake(0, 0, size.width, size.height)
            photosViewCellScrollView.contentInset = UIEdgeInsetsMake(y, 0, 0, 0)
        }else{
            photoView.frame = CGRectMake(0, 0, size.width, size.height)
            photosViewCellScrollView.contentSize = size
        }
    }
    
    ///  根据图片计算出图片在scrollView中应该显示的高度
    private func displaySize(image: UIImage) -> CGSize {
        let scrollViewWith = photosViewCellScrollView.bounds.width
        let scrollViewHeight = image.size.height * scrollViewWith / image.size.width
        

        return CGSizeMake(scrollViewWith, scrollViewHeight)
    }
    
    /// MARK:- 缩略图转换为中等图
    private func thumbnailChange2middleURL(url: NSURL) -> NSURL {
        
        // 1. 转换成 string
        var urlString = url.absoluteString
        
        // 2. 替换单词
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
    }
    
    private func restScrollView() {
        //重置photoView的transform属性
        photoView.transform = CGAffineTransformIdentity
        //重置photosViewCellScrollView的内容属性
        photosViewCellScrollView.contentSize = CGSizeZero
        photosViewCellScrollView.contentInset = UIEdgeInsetsZero
        photosViewCellScrollView.contentOffset = CGPointZero
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// cell中的scrollView
    lazy var photosViewCellScrollView: UIScrollView = UIScrollView()
    /// 放大图的imageView
    lazy var photoView: UIImageView = UIImageView()
    /// 站位图片的imageView
    lazy var placeHolderView: WQProgressImageView = WQProgressImageView()
    
}
extension WQPhotosViewCell {
    
    private func setupUI() {
        
        contentView.addSubview(photosViewCellScrollView)
        photosViewCellScrollView.addSubview(photoView)
        photosViewCellScrollView.addSubview(placeHolderView)
        var rect = self.contentView.bounds
        rect.size.width -= 20
        photosViewCellScrollView.frame = rect
        
        //设置scrollView的代理和缩放比例
        photosViewCellScrollView.delegate = self
        photosViewCellScrollView.maximumZoomScale = 2
        photosViewCellScrollView.minimumZoomScale = 0.5
        
        //图片允许交互
        photoView.userInteractionEnabled = true
        
        //有contentOffset属性的空间默认touch事件被手势屏蔽
        let tapGesture = UITapGestureRecognizer(target: self, action: "closeImageBrowser")
        photoView.addGestureRecognizer(tapGesture)
        
    }
    
    @objc private func closeImageBrowser() {
        photoViewDelegate?.photosViewDidTapImage()
    }
}

extension WQPhotosViewCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return photoView
    }
    
    
    //函数功能：放大就x，y ＝ 0 原点显示
    //        缩小就居中显示，offset ＝ 宽高差 * 0.5
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {

        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        
        // 设置间距
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
}